import { ModalForm, ProFormInstance, ProFormSelect } from '@ant-design/pro-components';

import { getAreasList } from '@/services/api/area';
import { getList } from '@/services/api/assets';
import { assignmentsEnd, assignmentsSearch, createAssignments } from '@/services/api/assignments';
import { getFilterUser } from '@/services/api/auth';
import { Alert, Button, Popconfirm } from 'antd';

import React, { useRef, useState } from 'react';
const FORM_ITEM = {
  userId: '',
  areaToken: '',
  assetToken: '',
  voiceBoxToken: '',
  token: '',
};
type CreateFormProps = {
  onCancel?: () => void;
  onSubmit?: (values?: API.CreateAssignmentsparams) => void;
  deviceToken: string;
};

const CreateForm: React.FC<CreateFormProps> = (props) => {
  const { onSubmit, deviceToken } = props;
  const formRef = useRef<ProFormInstance>();
  // 是否存在分配
  const [assignmentList, setAssignment] = useState<API.CreateAssignmentsparams>({
    ...FORM_ITEM,
  });
  // 释放
  const handleConfirmEnd = async () => {
    try {
      await assignmentsEnd(assignmentList.token!);
      if (onSubmit) {
        onSubmit();
      }
      // formRef.current?.resetFields();
      // 释放之后,重置表单,这里不是重置,而是从新设置空值,因表单本身存在默认值
      formRef.current?.setFieldsValue({
        ...FORM_ITEM,
      });
      setAssignment({
        ...FORM_ITEM,
      });
      Promise.resolve(null);
    } catch {
      Promise.resolve(null);
    }
  };
  // const [messageApi, contextHolder] = message.useMessage();
  // const { message } = App.useApp();

  return (
    <>
      <ModalForm<API.CreateAssignmentsparams>
        trigger={
          <Button size="small" type="primary">
            添加分配
          </Button>
        }
        request={async () => {
          const res = await assignmentsSearch(
            {
              pageSize: 1,
              page: 1,
              includeArea: true,
              includeAsset: true,
              includeCustomer: true,
              includeDevice: true,
              userIds: '',
            },
            {
              data: {
                assignmentStatuses: ['Active'],
                deviceTokens: [deviceToken],
              },
            },
          );
          const obj = res.results.length ? res.results[0] : null;
          let data = null;
          if (obj) {
            data = {
              userId: obj?.user?.userId,
              areaToken: obj?.ideviceAssignment?.area?.token,
              assetToken: obj?.ideviceAssignment?.asset?.token,
              voiceBoxToken: obj?.ideviceAssignment?.voiceBoxId,
              token: obj.ideviceAssignment?.token,
            };
          } else {
            data = {
              userId: null,
              areaToken: null,
              assetToken: null,
              voiceBoxToken: null,
              token: null,
            };
          }
          setAssignment(data);
          return data;
        }}
        formRef={formRef}
        modalProps={{
          destroyOnClose: true,
        }}
        // ModalForm 是 form 不是 modal，按钮是 form 的按钮，不是 button 的
        submitter={{
          submitButtonProps: { disabled: !!assignmentList.token },
        }}
        title={`添加分配/${deviceToken}`}
        onFinish={async (values: API.CreateAssignmentsparams) => {
          console.log(values);
          await createAssignments({
            ...values,
            metadata: {},
            deviceToken,
          });
          if (onSubmit) {
            onSubmit(values);
          }
          // messageApi.success('提交成功');
          // 返回true 则关闭
          return true;
        }}
        // initialValues={{
        //   ...assignmentList,
        // }}
      >
        {/* 存在分配的给出提示 */}
        {assignmentList.token && (
          <Alert
            style={{
              marginBottom: 10,
            }}
            action={
              <Popconfirm key={'del12'} title="确定释放吗" onConfirm={() => handleConfirmEnd()}>
                <Button color="warning" size="small" type="link">
                  去释放
                </Button>
              </Popconfirm>
            }
            message="设备最多只能存在一个已激活的分配，如需新增请先释放当前已有"
            type="warning"
            showIcon
          />
        )}
        <ProFormSelect
          name="userId"
          label="用户"
          request={async () => {
            const msg = await getFilterUser();
            const results = msg?.data;
            return results.map((item) => {
              return {
                label: item.username,
                value: item.id,
              };
            });
          }}
          placeholder="请选择"
          rules={[{ required: true, message: '请选择' }]}
        />
        <ProFormSelect
          name="areaToken"
          label="站点"
          request={async () => {
            const msg = await getAreasList({
              includeAreaType: false,
              includeAssignments: false,
              includeZones: false,
              rootOnly: false,
              page: 1,
              pageSize: 0,
            });
            const results = msg?.results;
            return results.map((item) => {
              return {
                label: item.name,
                value: item.token,
              };
            });
          }}
          placeholder="请选择"
          rules={[{ required: true, message: '请选择' }]}
        />
        <ProFormSelect
          name="assetToken"
          label="网关"
          request={async () => {
            const msg = await getList({
              includeAssetType: false,
              page: 1,
              pageSize: 0,
            });
            const results = msg?.results;
            return results.map((item) => {
              return {
                label: item.name,
                value: item.token,
              };
            });
          }}
          placeholder="请选择"
          rules={[{ required: true, message: '请选择' }]}
        />
        {/* <ProFormSelect
          name="voiceBoxToken"
          label="音箱"
          request={async () => {
            const msg = await getBoxsList({
              page: 1,
              pageSize: 0,
            });
            const results = msg?.results;
            return results.map((item) => {
              return {
                label: item.name,
                value: item.token,
              };
            });
          }}
          placeholder="请选择"
          rules={[{ required: true, message: '请选择' }]}
        /> */}
      </ModalForm>
    </>
  );
};

export default CreateForm;
